package com.open.pay.wechat.infrastructure.config;


import com.open.framework.exception.BusinessException;
import com.open.pay.common.util.Tuple2;
import com.open.pay.wechat.infrastructure.config.wxpaysdk.WXPay;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhang kaichao
 * @since 2021/2/24 11:48:27
 */
@Slf4j
public class WxPayService {

    private final Map<String, WxPayConfigStorageImpl> configStorageMap=new ConcurrentHashMap<>();

    /**
     * 进行相应的商户切换.
     */
    public WxPayService switchoverBuild(String mpId) {
        if(StringUtils.isBlank(mpId)){
            throw new BusinessException("appId不能为空");
        }
        if (this.configStorageMap.containsKey(mpId)) {
            WxPayConfigStorageHolder.set(mpId);
            return this;
        }
        WxPayConfigStorageHolder.remove();
        throw new BusinessException(String.format("无法找到对应【%s】的配置信息，请核实！", mpId));
    }

    public boolean switchover(String mpId) {
        if (this.configStorageMap.containsKey(mpId)) {
            WxPayConfigStorageHolder.set(mpId);
            return true;
        }
        WxPayConfigStorageHolder.remove();
        log.error("无法找到对应【{}】的配置信息，请核实！", mpId);
        return false;
    }

    public WxPayConfigStorageImpl getWxPayConfigStorage() {
        return this.configStorageMap.get(WxPayConfigStorageHolder.get());
    }

    public void setMultiConfigStorages(Map<String, WxPayConfigStorageImpl> configStorages) {
        this.setMultiConfigStorages(configStorages, configStorages.keySet().iterator().next());
    }

    public void setMultiConfigStorages(Map<String, WxPayConfigStorageImpl> configStorages, String defaultMpId) {
        this.configStorageMap.putAll(configStorages);
        WxPayConfigStorageHolder.set(defaultMpId);
    }

    public Tuple2<WXPay,WxPayConfigStorageImpl> getWxPay() {
        WxPayConfigStorageImpl wxPayConfig = this.configStorageMap.get(WxPayConfigStorageHolder.get());
        try {
            if (wxPayConfig.getUseSandbox()) {
                log.info("### ====>启动微信支付沙箱环境.");
                WXPay wxPay=new WXPay(wxPayConfig, wxPayConfig.getNotifyUrl(), true, true);
                return Tuple2.of(wxPay,wxPayConfig);
            }
            WXPay wxPay=new WXPay(wxPayConfig, wxPayConfig.getNotifyUrl());
            return Tuple2.of(wxPay,wxPayConfig);
        } catch (Exception e) {
            log.error("## /WxPayService getWxPay fail:",e);
            throw new BusinessException("支付sdk初始化失败");
        }finally {
            WxPayConfigStorageHolder.remove();
        }
    }

}
